import React, { useState, useEffect } from 'react';
import {
  Modal,
  Tree,
  Button,
  Space,
  Toast,
  Typography,
  Spin,
  Empty,
  Divider,
  Tag,
} from '@douyinfe/semi-ui';
import { IconUser, IconUserGroup, IconKey } from '@douyinfe/semi-icons';

const { Title, Text } = Typography;

interface PermissionNode {
  key: string;
  label: string;
  value: string;
  children?: PermissionNode[];
  type?: number; // 1-菜单权限，2-按钮权限，3-数据权限
  checked?: boolean;
}

interface PermissionAssignmentProps {
  visible: boolean;
  onCancel: () => void;
  targetType: 'user' | 'role'; // 分配目标类型：用户或角色
  targetId?: number; // 目标ID
  targetName?: string; // 目标名称
  onSuccess?: () => void;
}

const PermissionAssignment: React.FC<PermissionAssignmentProps> = ({
  visible,
  onCancel,
  targetType,
  targetId,
  targetName,
  onSuccess,
}) => {
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [permissionTree, setPermissionTree] = useState<PermissionNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [originalCheckedKeys, setOriginalCheckedKeys] = useState<string[]>([]);

  // 加载权限树数据
  const loadPermissionTree = async () => {
    if (!targetId) return;
    
    setLoading(true);
    try {
      // 根据目标类型调用不同的API
      let response;
      if (targetType === 'user') {
        // 调用用户权限API
        response = await fetch(`/api/user-roles/user/${targetId}/permissions`);
      } else {
        // 调用角色权限API
        response = await fetch(`/api/role-permissions/role/${targetId}/tree`);
      }
      
      if (!response.ok) {
        throw new Error('获取权限数据失败');
      }
      
      const result = await response.json();
      if (result.success) {
        const treeData = result.data.permissionTree || [];
        setPermissionTree(treeData);
        
        // 设置已选中的权限
        const checked = extractCheckedKeys(treeData);
        setCheckedKeys(checked);
        setOriginalCheckedKeys([...checked]);
        
        // 默认展开所有节点
        const allKeys = extractAllKeys(treeData);
        setExpandedKeys(allKeys);
      } else {
        throw new Error(result.message || '获取权限数据失败');
      }
    } catch (error) {
      console.error('加载权限树失败:', error);
      Toast.error('加载权限数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 提取已选中的权限键
  const extractCheckedKeys = (nodes: PermissionNode[]): string[] => {
    const keys: string[] = [];
    const traverse = (nodeList: PermissionNode[]) => {
      nodeList.forEach(node => {
        if (node.checked) {
          keys.push(node.key);
        }
        if (node.children) {
          traverse(node.children);
        }
      });
    };
    traverse(nodes);
    return keys;
  };

  // 提取所有权限键
  const extractAllKeys = (nodes: PermissionNode[]): string[] => {
    const keys: string[] = [];
    const traverse = (nodeList: PermissionNode[]) => {
      nodeList.forEach(node => {
        keys.push(node.key);
        if (node.children) {
          traverse(node.children);
        }
      });
    };
    traverse(nodes);
    return keys;
  };

  // 处理权限选择变化
  const handleCheck = (checkedKeys: string[]) => {
    setCheckedKeys(checkedKeys);
  };

  // 保存权限分配
  const handleSave = async () => {
    if (!targetId) return;
    
    setSubmitting(true);
    try {
      const permissionIds = checkedKeys.map(key => parseInt(key));
      
      let response;
      if (targetType === 'user') {
        // 分配用户权限
        response = await fetch('/api/user-roles/assign-permissions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: targetId,
            permissionIds,
          }),
        });
      } else {
        // 分配角色权限
        response = await fetch('/api/role-permissions/assign', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roleId: targetId,
            permissionIds,
          }),
        });
      }
      
      if (!response.ok) {
        throw new Error('保存权限失败');
      }
      
      const result = await response.json();
      if (result.success) {
        Toast.success('权限分配成功');
        onSuccess?.();
        onCancel();
      } else {
        throw new Error(result.message || '保存权限失败');
      }
    } catch (error) {
      console.error('保存权限失败:', error);
      Toast.error('保存权限失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 重置权限选择
  const handleReset = () => {
    setCheckedKeys([...originalCheckedKeys]);
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    const allKeys = extractAllKeys(permissionTree);
    if (checkedKeys.length === allKeys.length) {
      setCheckedKeys([]);
    } else {
      setCheckedKeys(allKeys);
    }
  };

  // 渲染权限节点
  const renderTreeNode = (node: PermissionNode) => {
    const getTypeTag = (type?: number) => {
      switch (type) {
        case 1:
          return <Tag color="blue" size="small">菜单</Tag>;
        case 2:
          return <Tag color="green" size="small">按钮</Tag>;
        case 3:
          return <Tag color="orange" size="small">数据</Tag>;
        default:
          return null;
      }
    };

    return (
      <div className="flex items-center justify-between w-full">
        <span className="flex items-center gap-2">
          {node.label}
          {getTypeTag(node.type)}
        </span>
      </div>
    );
  };

  // 监听弹窗显示状态
  useEffect(() => {
    if (visible && targetId) {
      loadPermissionTree();
    } else {
      // 重置状态
      setPermissionTree([]);
      setCheckedKeys([]);
      setExpandedKeys([]);
      setOriginalCheckedKeys([]);
    }
  }, [visible, targetId, targetType]);

  const hasChanges = JSON.stringify(checkedKeys.sort()) !== JSON.stringify(originalCheckedKeys.sort());

  return (
    <Modal
      title={
        <div className="flex items-center gap-2">
          {targetType === 'user' ? <IconUser /> : <IconUserGroup />}
          <span>
            为{targetType === 'user' ? '用户' : '角色'}「{targetName}」分配权限
          </span>
        </div>
      }
      visible={visible}
      onCancel={onCancel}
      width={600}
      height={700}
      footer={
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-2">
            <Button size="small" onClick={handleSelectAll}>
              {checkedKeys.length === extractAllKeys(permissionTree).length ? '取消全选' : '全选'}
            </Button>
            <Button size="small" onClick={handleReset} disabled={!hasChanges}>
              重置
            </Button>
            <Text type="tertiary" size="small">
              已选择 {checkedKeys.length} 项权限
            </Text>
          </div>
          <Space>
            <Button onClick={onCancel}>取消</Button>
            <Button 
              type="primary" 
              onClick={handleSave}
              loading={submitting}
              disabled={!hasChanges}
            >
              保存
            </Button>
          </Space>
        </div>
      }
    >
      <div className="h-full flex flex-col">
        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <Spin size="large" />
          </div>
        ) : permissionTree.length === 0 ? (
          <div className="flex-1 flex items-center justify-center">
            <Empty 
              image={<IconKey size="extra-large" />}
              title="暂无权限数据"
              description="请先配置系统权限"
            />
          </div>
        ) : (
          <div className="flex-1 overflow-auto">
            <div className="mb-4 p-3 bg-gray-50 rounded">
              <div className="flex items-center gap-2 mb-2">
                <IconKey />
                <Text strong>权限说明</Text>
              </div>
              <div className="text-sm text-gray-600 space-y-1">
                <div>• <Tag color="blue" size="small">菜单</Tag> 菜单访问权限</div>
                <div>• <Tag color="green" size="small">按钮</Tag> 操作按钮权限</div>
                <div>• <Tag color="orange" size="small">数据</Tag> 数据访问权限</div>
              </div>
            </div>
            
            <Divider margin="12px" />
            
            <Tree
              treeData={permissionTree}
              checkable
              multiple
              checkedKeys={checkedKeys}
              expandedKeys={expandedKeys}
              onCheck={handleCheck}
              onExpand={setExpandedKeys}
              renderFullLabel={renderTreeNode}
              checkRelation="related"
              defaultExpandAll
            />
          </div>
        )}
      </div>
    </Modal>
  );
};

export default PermissionAssignment;